/*
 * Copyright (C) 2009 Show SMS open source project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bydavy.android.showsms;

//~--- non-JDK imports --------------------------------------------------------

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.Service;

import android.content.Intent;
import android.content.SharedPreferences;

import android.os.IBinder;
import android.os.RemoteException;

import android.preference.PreferenceManager;

import com.bydavy.model.showsms.SSMessage;
import com.bydavy.util.showsms.Log;
import com.bydavy.util.showsms.WakeLockEasier;

//~--- JDK imports ------------------------------------------------------------

import java.util.Iterator;
import java.util.Vector;

/**
 * Service launched by the PreviewActivity
 *  This service store all <SSMessage> received by the PreviewActivity after the first SMS.
 * <SSMessage> are stored like in a FIFO
 * This service keep the WakeLock and KeyguardLock status too.
 * @version        1.0, 09/06/27
 * @author         Davy L.
 */
public class PreviewService extends Service {
    //~--- fields -------------------------------------------------------------

    /** Vector that contains all Messages */
    private Vector<SSMessage> allMessages = null;

    /** AIDL Service that manage <SSMessage> */
    private final IPreviewService.Stub mBinder = new IPreviewService.Stub() {

        /**
         * Store a <SSMessage> in the <PreviewService>
         *  <SSMessage> are stored like in a FIFO
         *
         * @param message message to store
         */
        public void addMessage(SSMessage message) throws RemoteException {
            Log.d("PreviewService: addMessage | " + message.getBody());
            allMessages.add(message);
        }
        ;

        /**
         * Store a <SSMessage> contained in the Intent in the <PreviewService>
         *  <SSMessage> are stored like in a FIFO
         *
         * @param message message to store
         */
        public void addMessageFromIntent(Intent intent) throws RemoteException {
            SSMessage message = SSMessage.constructFromBundle(intent.getExtras());

            Log.d("PreviewService: addMessage | " + message.getBody());
            allMessages.add(message);
        }
        ;

        /**
         * Retrieve a <SSMessage> from the <PreviewService>
         *  <SSMessage> are retrieve like in a FIFO
         *  The read is destructive
         *
         * @return SSMessage Retrieved message
         */
        public SSMessage getMessage() throws RemoteException {
            Log.d("PreviewService: getMessage");

            Iterator<SSMessage> i = allMessages.iterator();

            if (i.hasNext()) {
                SSMessage messageToReturn = (SSMessage) i.next();

                i.remove();
                Log.d("PreviewService: getMessage |" + messageToReturn.toString());

                return messageToReturn;
            }

            return null;
        }

        /**
         * Count the number of <SSMessage> currently sotred in the <PreviewService>
         *
         * @return int How many <SSMessage> are stored in the <PreviewService>
         */
        @Override
        public int messageCount() throws RemoteException {
            return allMessages.size();
        }
    };

    /** KeyguardLock */
    private KeyguardLock lock;

    /** unlock  status loaded from the SharedPreferences */
    private boolean unlock;

    /** wake up  status loaded from the SharedPreferences */
    private boolean wake_up;

    //~--- methods ------------------------------------------------------------

    /**
     * Method description
     *
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.v("PreviewService: onCreate");
        loadPreferences();

        if (unlock) {

            // Disable screen lock
            KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);

            lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
            lock.disableKeyguard();
        }

        if (wake_up) {
            WakeLockEasier.acquireScreenWakeLockWithWakeUp(this);
        } else {
            WakeLockEasier.acquireScreenWakeLock(this);
        }

        allMessages = new Vector<SSMessage>();
    }

    /**
     * Method description
     *
     */
    private void loadPreferences() {
        SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        // loading wake up status from SharedPreferences
        boolean wake_up_def = Boolean.valueOf(getString(R.preferences.wake_up_def));

        wake_up = mySharedPreferences.getBoolean(getString(R.preferences.wake_up_key), wake_up_def);

        // loading unlock status from SharedPreferences
        boolean unlock_def = Boolean.valueOf(getString(R.preferences.unlock_def));

        unlock = mySharedPreferences.getBoolean(getString(R.preferences.unlock_key), unlock_def);
    }

    /**
     * Method description
     *
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v("PreviewService: onDestroy");
        WakeLockEasier.release();
    }

    /**
     * Method description
     *
     *
     * @param intent
     * @param startId
     */
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.v("PreviewService: onStart");
    }

    /**
     * Method description
     *
     *
     * @param intent
     *
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {

        // Select the interface to return.  If your service only implements
        // a single interface, you can just return it here without checking
        // the Intent.
        if (IPreviewService.class.getName().equals(intent.getAction())) {
            return mBinder;
        }

        return null;
    }
}
